//
//  ABSnomPhone.m
//  snomPhone
//
//  Created by Daniel Hazelbaker on 11/4/08.
//  Copyright 2008 Blue Box Moon. All rights reserved.
//

#import "ABSnomPhone.h"
#import "BMSnomPhone.h"
#import "BMPreferences.h"
#import "preferences.h"
#import <AddressBook/AddressBook.h>


@implementation ABSnomPhone


//
// Initialize this object and connect to the phone.
//
- (id)init
{
    if ([super init] == nil)
	return nil;

    NS_DURING
	snomPhone = (BMSnomPhone *)[NSConnection rootProxyForConnectionWithRegisteredName:@"com.blueboxmoon.snomPhone" host:nil];
    NS_HANDLER
	snomPhone = nil;
    NS_ENDHANDLER

    return self;
}


//
// Free memory used by this address book plug-in.
//
- (void)dealloc
{
    if (snomPhone != nil) {
	[snomPhone release];
	snomPhone = nil;
    }

    [super dealloc];
}


//
// This action works with phone numbers.
//
- (NSString *)actionProperty
{
    return kABPhoneProperty;
}


//
// Our menu title will look like "Dial 555-5555"
//
- (NSString *)titleForPerson:(ABPerson *)person identifier:(NSString *)identifier
{
    ABMultiValue    *values;
    NSString	    *value;


    if (snomPhone == nil)
	return @"- Phone Unavailable -";

    //
    // Get the phone number.
    //
    values = [person valueForProperty:[self actionProperty]];
    value = [values valueAtIndex:[values indexForIdentifier:identifier]];

    //
    // Build and return the title.
    //
    return [NSString stringWithFormat:@"Dial %@", value];    
}


//
// This method is called when the user selects your action. As above, this method
// is passed information about the data item rolled over.
//
- (void)performActionForPerson:(ABPerson *)person identifier:(NSString *)identifier
{
    NSMutableString *value;
    NSCharacterSet  *nonNumericSet;
    ABMultiValue    *values;
    NSRange	    range;


    //
    // Get the phone number.
    //
    values = [person valueForProperty:[self actionProperty]];
    value = [NSMutableString stringWithString:[values valueAtIndex:[values indexForIdentifier:identifier]]];

    //
    // Generate a character set that is everything but the numbers.
    //
    nonNumericSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    nonNumericSet = [nonNumericSet invertedSet];

    //
    // Strip out everything but numbers.
    //
    range = [value rangeOfCharacterFromSet:nonNumericSet];
    for (range = [value rangeOfCharacterFromSet:nonNumericSet]; range.location != NSNotFound; range = [value rangeOfCharacterFromSet:nonNumericSet]) {
	[value deleteCharactersInRange:range];
    }

    //
    // Dial the number.
    //
    [snomPhone dialPhoneNumber:value];
}


//
// Optional. Your action will always be enabled in the absence of this method. As
// above, this method is passed information about the data item rolled over.
//
- (BOOL)shouldEnableActionForPerson:(ABPerson *)person identifier:(NSString *)identifier
{
    return YES;
}

@end
